package com.hangwei.paperless.view.repair;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hangwei.paperless.MainRepairActivity;
import com.hangwei.paperless.R;
import com.hangwei.paperless.adapter.FinalAdapter;
import com.hangwei.paperless.model.bean.BasicInfoBean;
import com.hangwei.paperless.model.bean.CardToSeal;
import com.hangwei.paperless.model.bean.DRSInfo;
import com.hangwei.paperless.model.bean.MainRepairList;
import com.hangwei.paperless.model.bean.RecordListBean;
import com.hangwei.paperless.presenter.StaticPresenter;
import com.hangwei.paperless.utils.Constants;
import com.hangwei.paperless.utils.NFCCallBack;
import com.hangwei.paperless.view.BaseView;
import com.hangwei.paperless.view.SealHelper;
import com.twelve.all.net.CallBack;
import com.twelve.all.utils.LoadingDialog;
import com.twelve.all.utils.LogUtil;
import com.twelve.all.utils.SPKey;
import com.twelve.all.utils.SPUtil;
import com.twelve.all.utils.ToastUtil;
import com.twelve.all.utils.Tools;

import java.util.List;

import static com.hangwei.paperless.MainRepairActivity.mStepId;

/**
 * Created by 张龙臣 on 2020/10/14.
 */

public class FinalCheck extends BaseView<MainRepairActivity, List<RecordListBean>> {

    private FinalAdapter mAdapter;
    private EditText mEtRemark;
    private LinearLayout mLlOpen;
    private RelativeLayout mRlInspectorSeal;
    private RecyclerView mRecyclerView;

    public FinalCheck(MainRepairActivity activity) {
        super(activity);
    }

    private static final String currentTab = "8";


    @Override
    protected View initView() {
        View inflate = LayoutInflater.from(mActivity).inflate(R.layout.page_final_check, null);
//        mEtRemark = inflate.findViewById(R.id.etRemark);
//        RelativeLayout rlOpen = inflate.findViewById(R.id.rlOpen);
//        mRlInspectorSeal = inflate.findViewById(R.id.rlInspectorSeal);
        mLlOpen = inflate.findViewById(R.id.llOpen);
        mLlOpen.setOnClickListener(this);
        mRecyclerView = inflate.findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        mAdapter = new FinalAdapter(null) {
            @Override
            protected void seal(final RecordListBean item, final int stampRole, final String resultVal) {
                //判断是否是当前执行行
                if (!item.id.equals(mStepId)) {
                    return;
                }
                mActivity.sealByCard(item.id, new NFCCallBack() {
                    @Override
                    public void onCallBack(List<CardToSeal.StampBean> stampIds, String userId) {
                        if (stampIds==null||stampIds.size()==0){
                            ToastUtil.showCenterToast("无印章！");
                        }else {
                            final LoadingDialog loadingDialog = new LoadingDialog(mActivity);
                            loadingDialog.show();
                            String userId0 = SPUtil.getString(SPKey.Account.USER_ID);
                            StaticPresenter.stampRoutingSheetStep(userId0, mActivity.getBillId(), item.id, stampRole, userId, stampIds.get(0).stampId, resultVal, new CallBack<Object>() {
                                @Override
                                public void onCompleted(Object o) {
                                    loadingDialog.dismiss();
                                    mActivity.closeBottomPop();
                                    initData();
                                }

                                @Override
                                public void onError() {
                                    loadingDialog.dismiss();
                                }
                            });
                        }
                    }
                });
//                //选印章
//                if (App.stamps != null && App.stamps.size() > 0) {
//                    //有印章
//                    MainBottomPopupWindow mainBottomPopupWindow = mActivity.showBottomPopupWindow(BottomPopType.Seal);
//                    mainBottomPopupWindow.setOnSealListener(new MainBottomPopupWindow.OnSealListener() {
//                        @Override
//                        public void onSeal(String stampId) {
//                            final LoadingDialog loadingDialog = new LoadingDialog(mActivity);
//                            loadingDialog.show();
//                            String userId = SPUtil.getString(SPKey.Account.USER_ID);
//                            StaticPresenter.stampRoutingSheetStep(userId, mActivity.getBillId(), item.id, stampRole, userId, stampId, resultVal, new CallBack<Object>() {
//                                @Override
//                                public void onCompleted(Object o) {
//                                    loadingDialog.dismiss();
//                                    mActivity.closeBottomPop();
//                                    initData();
//                                }
//
//                                @Override
//                                public void onError() {
//                                    loadingDialog.dismiss();
//                                }
//                            });
//                        }
//                    });
//                } else {
//                    ToastUtil.showCenterToast("无印章");
////                    String signPic = SPUtil.getString(SPKey.Account.SIGN_PIC);
////                    if (TextUtils.isEmpty(signPic)) {
////
////                    } else {
////
////                    }
//                }
            }
        };
        mAdapter.setEnableLoadMore(false);
        mAdapter.addFooterView(getFootView());
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                List<RecordListBean> data = mAdapter.getData();
                if (data.size() > 0) {
                    String id = data.get(data.size() - 1).id;
                    final long currentTimeMillis = System.currentTimeMillis();
                    StaticPresenter.getExRoutingSheetStepByPage(mUserId, mActivity.getBillId(), "down", id, Constants.PAGE_SIZE, new CallBack<List<RecordListBean>>() {
                        @Override
                        public void onCompleted(List<RecordListBean> listBeans) {
                            long deTime = System.currentTimeMillis() - currentTimeMillis;
//                            if (deTime < 500)
//                                SystemClock.sleep(500 - deTime);
                            mAdapter.addData(listBeans);
                            if (listBeans.size() >= Constants.PAGE_SIZE) {
                                mAdapter.loadMoreComplete();
                            } else {
                                mAdapter.loadMoreEnd(false);
                            }
                        }

                        @Override
                        public void onError() {
//                            mAdapter.setEnableLoadMore(true);
                        }
                    });
                }
            }
        }, mRecyclerView);
        mRecyclerView.setAdapter(mAdapter);
        initData();
        getSealData();
        return inflate;
    }
    private View getFootView() {
        View inflate = LayoutInflater.from(mActivity).inflate(R.layout.footer_final, null);
        mEtRemark = inflate.findViewById(R.id.etRemark);
        mRlInspectorSeal = inflate.findViewById(R.id.rlInspectorSeal);
        return inflate;
    }
    private void getSealData(){
        StaticPresenter.getRoutingSheetStep(mUserId, mActivity.getBillId(),8,0,1,1, new CallBack<MainRepairList>() {
            @Override
            public void onCompleted(MainRepairList info) {
                if (info!=null){
                    mEtRemark.setText(Tools.checkedString(info.remark));
                    SealHelper sealHelper = new SealHelper(mActivity) {
                        @Override
                        protected void onSeal() {
                            FinalCheck.this.mActivity.sealByCard("", new NFCCallBack() {
                                @Override
                                public void onCallBack(List<CardToSeal.StampBean> stampIds, String userId) {
                                    if (stampIds==null||stampIds.size()==0){
                                        ToastUtil.showCenterToast("无印章！");
                                    }else {
                                        final LoadingDialog dialog = new LoadingDialog(mActivity);
                                        dialog.show();
                                        String userId0 = SPUtil.getString(SPKey.Account.USER_ID);
                                        String remark = mEtRemark.getText().toString().trim();
                                        StaticPresenter.stampRoutingSheetContent(userId0, FinalCheck.this.mActivity.getBillId(), 5, "2", userId, stampIds.get(0).stampId, remark, new CallBack<Object>() {
                                            @Override
                                            public void onCompleted(Object o) {
                                                dialog.dismiss();
                                                FinalCheck.this.mActivity.finish();
                                            }

                                            @Override
                                            public void onError() {
                                                dialog.dismiss();
                                            }
                                        });
                                    }
                                }
                            });
                        }
                    };
                    sealHelper.bindData(new SealHelper.SealBean(true,info.inspectorStampId,info.inspectorId,info.inspectorStampTypeCode,info.inspectorStampCode,info.inspectorDate,info.inspector,true));
                    mRlInspectorSeal.removeAllViews();
                    mRlInspectorSeal.addView(sealHelper.getItemView());
                }
            }

            @Override
            public void onError() {

            }
        });
    }

    @Override
    public void bindData(List<RecordListBean> recordList) {
        mAdapter.setNewData(recordList);
        if (recordList != null && recordList.size() > 0)
            checkCanOpen(recordList.get(0).id);
        else mLlOpen.setVisibility(View.GONE);
    }
    private void checkCanOpen(String id) {
        StaticPresenter.getExRoutingSheetStepByPage(mUserId, mActivity.getBillId(), "up", id,  Constants.PAGE_SIZE, new CallBack<List<RecordListBean>>() {
            @Override
            public void onCompleted(List<RecordListBean> listBeans) {
                if (listBeans == null || listBeans.size() == 0)
                    mLlOpen.setVisibility(View.GONE);
                else mLlOpen.setVisibility(View.VISIBLE);
            }

            @Override
            public void onError() {
                mLlOpen.setVisibility(View.GONE);
            }
        });
    }

    private void initData() {
        final LoadingDialog dialog = new LoadingDialog(mActivity);
        dialog.show();
        final String userId = SPUtil.getString(SPKey.Account.USER_ID);
        StaticPresenter.getExRoutingSheetSteps(userId, mActivity.getBillId(), new CallBack<List<RecordListBean>>() {
            @Override
            public void onCompleted(final List<RecordListBean> recordList) {
                bindData(recordList);
                StaticPresenter.getRoutingSheetInfo(userId, mActivity.getBillId(), new CallBack<BasicInfoBean>() {
                    @Override
                    public void onCompleted(BasicInfoBean basicInfoBean) {
                        dialog.dismiss(); if (basicInfoBean!=null){
                            MainRepairActivity.pwoNo = basicInfoBean.pwoNo;
                        }

                        //对比确认当前执行行
                        for (RecordListBean recordListBean : recordList) {
                            LogUtil.i("recordListBean.id =    ", recordListBean.id);
                            LogUtil.i("basicInfoBean.curExId =    ", basicInfoBean.curExId);
                            if (recordListBean.id != null && recordListBean.id.equals(basicInfoBean.curExId)) {
                                LogUtil.i("--------------111------------");

                                recordListBean.isCurrent = true;
//                                if (recordListBean.id != null && !recordListBean.id.equals(mStepId)) {
//                                    mDrsHasSaved = false;//执行行改变
//                                }
                                mStepId = recordListBean.id;
                                if (recordListBean.isDrs) {
                                    LogUtil.i("------------2222--------------");
                                    //获取DRS
                                    StaticPresenter.getDrsAndAttachmentList(userId, mStepId, 0, new CallBack<DRSInfo>() {
                                        @Override
                                        public void onCompleted(DRSInfo drsInfo) {
                                        }

                                        @Override
                                        public void onError() {

                                        }
                                    });
                                }
                            } else recordListBean.isCurrent = false;
                        }
                        mAdapter.notifyDataSetChanged();
                        mAdapter.setEnableLoadMore(true);
                    }

                    @Override
                    public void onError() {
                        dialog.dismiss();
                    }
                });
            }

            @Override
            public void onError() {
                dialog.dismiss();
            }
        });
    }

    @Override
    protected void isNotFastClick(View v) {
        switch (v.getId()) {
            case R.id.llOpen:
                List<RecordListBean> data = mAdapter.getData();
                if (data.size() > 0) {
                    final LoadingDialog dialog = new LoadingDialog(mActivity);
                    dialog.show();
                    String stepId = data.get(0).id;
                    StaticPresenter.getExRoutingSheetStepByPage(mUserId, mActivity.getBillId(), "up", stepId,  Constants.PAGE_SIZE, new CallBack<List<RecordListBean>>() {
                        @Override
                        public void onCompleted(List<RecordListBean> listBeans) {
                            dialog.dismiss();
                            if (listBeans == null || listBeans.size() <Constants.PAGE_SIZE) {
                                mLlOpen.setVisibility(View.GONE);
                                List<RecordListBean> beans = mAdapter.getData();
                                assert listBeans != null;
                                beans.addAll(0, listBeans);
                                mAdapter.setNewData(beans);
                            } else {
                                List<RecordListBean> beans = mAdapter.getData();
                                beans.addAll(0, listBeans);
                                mAdapter.setNewData(beans);
                            }
                        }

                        @Override
                        public void onError() {
                            dialog.dismiss();
                        }
                    });
                }
                break;
        }
    }

}
